//
//  BrowseElement.m
//  SolarSeek
//
//  Created by Erick Fejta on 05/06/13.
//  Copyright 2005 __MyCompanyName__. All rights reserved.
//

#import "BrowseView.h"
#import "BrowseElement.h"
#import "SolarSeekApplication.h"
#import "ApplicationDefaults.h"
#import "SearchesView.h"
#import "FriendsSourceListElement.h"
#import "SearchesController.h"
#import "SolarSeekEngine.h"

@interface BrowseElement (Private)
- (void)updateAndSave:(BOOL)save;
@end

@implementation BrowseElement 

- (id)initWithView:(NSView *)view peer:(Peer *)p browser:(NSBrowser *)b saveImmediately:(BOOL)save{
	if(self = [super initWithView:view]) {
		peer = [p retain];
		browser = [b retain];
		[self updateAndSave:save];
		cellsSelected = nil;
		[peer addObserver:self forKeyPath:@"countFiles" options:nil context:nil];
		waiting = save;
		
		[self setAutosaves:YES];
	}
	return self;
}

- (void)dealloc {
	[peer removeObserver:self forKeyPath:@"countFiles"];
	[peer release];
	[browser release];

	[super dealloc];
}

- (BOOL)autosaves { return autosaves; }
- (void)setAutosaves:(BOOL)b { 
	autosaves = b; 
	[(BrowseView *)[self view] setButtonRefreshEnabled:autosaves==NO];
}

- (BOOL)waiting { return waiting; }
- (void)setWaiting:(BOOL)w {
	waiting = w;
}

- (void)updateAndSave:(BOOL)save {
	unsigned test = [[peer sharesTreeRoot] countSharesThisAndSubLevels];
	if(test != count) {
		count = test;
		[NSApp updateSourceListElement:self];
		[browser loadColumnZero];
		[self willChangeValueForKey:@"shares"];
		[self didChangeValueForKey:@"shares"];
		if(save && [self autosaves] 
				&& [[NSUserDefaults standardUserDefaults] boolForKey:SolarSeekDefaultSaveSearches]) {
			@synchronized(self) {
				if([self autosaves]) 
					[self saveAutomatically];
				
			}
		}
	}
	count2 = test;
	[self setAutosaves:NO];
}


- (void)removeFromSourceList { 
	[self retain];
	[(SearchesView *)[NSApp viewSearches] endBrowseElement:self];
	[self autorelease];
}

- (void)update {
	[self updateAndSave:YES];
}

- (void)scheduleUpdate {
	[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(update) object:nil];
	[self performSelector:@selector(update) withObject:nil afterDelay:3.0];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
	[self performSelectorOnMainThread:@selector(scheduleUpdate) withObject:nil waitUntilDone:NO];
}

- (void)setSelected:(BOOL)sel {
	if(sel) {
		count2 = [[peer sharesTreeRoot] countSharesThisAndSubLevels];
		[browser setDelegate:self];
		[browser setTarget:self];
		[browser setDoubleAction:@selector(clickDouble:)];
		[browser setAction:@selector(clickSingle:)];
		[browser setAllowsMultipleSelection:NO];
		[browser loadColumnZero];
		[self setAutosaves:[self autosaves]];
	}
	else {
		[browser loadColumnZero]; // Pal: TODO - save column selection
		[browser setDelegate:nil];
		[browser setTarget:nil];
	}
	[super setSelected:sel];
	
}



- (ShareTree *)shareTreeCurrent { 
	int column = [browser selectedColumn];
	ShareTree *st = [self shareTreeAtColumn:column]; 
	if(column >= 0) {
		int row = [browser selectedRowInColumn:column];
		if(row >= 0)
			st = [[st subtrees] objectAtIndex:row];
	}
	return st;
}

- (NSImage *)icon { return [[self peer] icon]; } //fejta: TODO: change name.
- (NSString *)name { return [[peer name] stringByAppendingFormat:@" (%d)",count2]; }
- (NSString *)titleWindow { return [@"Browsing " stringByAppendingString:[peer name]]; }
- (NSArray *)participants { return [NSArray arrayWithObject:peer]; }
- (NSArray *)shares { return [[self shareTreeCurrent] sharesThisAndSubLevels]; }

- (ShareTree *)shareTreeAtColumn:(int)col {
	if(col<=0) {
		return [peer sharesTreeRoot];
	}
	else {
		ShareTree *st = [self shareTreeAtColumn:col-1];
		int index = [browser selectedRowInColumn:col-1];
		return [[st subtrees] objectAtIndex:index];
	}
}

- (void)clickSingle:(id)sender {
	[self willChangeValueForKey:@"shares"];
	[self didChangeValueForKey:@"shares"];
}

- (void)clickDouble:(id)sender {
	[self clickSingle:sender];
	[[NSAlert alertWithMessageText:@"Not Implemented"defaultButton:@"OK" alternateButton:nil otherButton:nil informativeTextWithFormat:@"Double clicking will have you download all files contained within these folders in the future.  It is currently not finished."]
		beginSheetModalForWindow:[NSApp keyWindow] modalDelegate:nil didEndSelector:nil contextInfo:nil];
}


- (Peer *)peer { return peer; }	

- (void)performSaveAutomatically {
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	[NSThread setThreadPriority:0.1];
	NS_DURING
		[FriendsSourceListElement savePeerInForeground:peer];
	NS_HANDLER
		NSLog(@"%@",localException);
		NSLog(@"Save aborted.  Continuing...");
	NS_ENDHANDLER
	[pool release];
}

- (void)saveAutomatically {
	[NSThread detachNewThreadSelector:@selector(performSaveAutomatically) toTarget:self withObject:nil];
}

- (id)search { return nil; }

- (void)savePanelDidEnd:(NSSavePanel *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo {
	if(returnCode==NSOKButton) {
		[[FriendsSourceListElement friendsSourceListElementShared] savePeer:[self peer] toPath:[sheet filename]];
	}
}

- (void)save {
	NSSavePanel *sp = [NSSavePanel savePanel];
	[sp setRequiredFileType:@"browse.plist"];
	[sp setCanCreateDirectories:YES];
	[sp beginSheetForDirectory:nil file:nil modalForWindow:[NSApp keyWindow] modalDelegate:self didEndSelector:@selector(savePanelDidEnd:returnCode:contextInfo:) contextInfo:nil];
}

#pragma mark Browser delegate

- (void)browser:(NSBrowser *)sender willDisplayCell:(NSBrowserCell *)cell atRow:(int)row column:(int)column {
	ShareTree *parent = [self shareTreeAtColumn:column];
	ShareTree *leaf = [[parent subtrees] objectAtIndex:row];
	[cell setLeaf:[[leaf subtrees] count]==0];
	[cell setStringValue:[leaf pathComponentLast]];
//	[cell setTag:row];
}

- (int)browser:(NSBrowser *)sender numberOfRowsInColumn:(int)column {
	ShareTree *st = [self shareTreeAtColumn:column];
	return [[st subtrees] count];
}

- (NSString *)browser:(NSBrowser *)sender titleOfColumn:(int)column {
	return [[self shareTreeAtColumn:column] pathComponentLast];
}


- (IBAction)refresh:(id)sender {
	[self setAutosaves:YES];
	[[[NSApp engine] searchesController] browseUser:[[self peer] name]];
}

@end
